package com.demo.javase.day09;

/**
 * Java之instanceof运算符案例演示
 *
 * @Author bug菌
 * @Date 2023-11-08 23:18
 */
public class InstanceofTest {

    public static void main(String[] args) {
        Object obj = new Integer(10);
        System.out.println(isInstanceOf(obj, Integer.class)); // 输出true
        System.out.println(isInstanceOf(obj, Number.class)); // 输出true
        System.out.println(isInstanceOf(obj, String.class)); // 输出false

        Integer i = convert(obj, Integer.class); // 强制类型转换
        System.out.println(i); // 输出10
    }

    public static boolean isInstanceOf(Object obj, Class<?> clazz) {
        return clazz.isInstance(obj);
    }

    public static <T> T convert(Object obj, Class<T> clazz) {
        if (clazz.isInstance(obj)) {
            return clazz.cast(obj);
        } else {
            throw new ClassCastException(obj.getClass().getName() + " cannot be cast to " + clazz.getName());
        }
    }
}
